package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-07-09
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneAndTowSubject() {
        //查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> allOneSubject = baseMapper.selectList(wrapperOne);
        //查询所有二级分类
        QueryWrapper<EduSubject> wrapperTow = new QueryWrapper<>();
        wrapperTow.ne("parent_id","0");
        List<EduSubject> allTwoSubject = baseMapper.selectList(wrapperTow);
        //封装最终数据
        List<OneSubject> allSubject = new ArrayList<>();
        for(EduSubject oneItem:allOneSubject){
            OneSubject oneSubject = new OneSubject();
            oneSubject.setId(oneItem.getId());
            oneSubject.setTitle(oneItem.getTitle());
            for(EduSubject twoItem:allTwoSubject){
                if(twoItem.getParentId().equals(oneItem.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    twoSubject.setId(twoItem.getId());
                    twoSubject.setTitle(twoItem.getTitle());
                    oneSubject.getTwoSubjectList().add(twoSubject);
                }
            }
            allSubject.add(oneSubject);
        }
        return allSubject;
    }
}
